<template>
  <div class="app-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>岗位管理</el-breadcrumb-item>
    </el-breadcrumb>
    <br>
    <!--    模糊查询模块-->
    <el-form v-show="showTable" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="岗位编码" prop="deptName">
        <el-input
          v-model="queryParams.postCode"
          placeholder="请输入岗位编码"
          clearable
          size="small"
          @clear="loadPost"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="岗位名称" prop="deptName">
        <el-input
          v-model="queryParams.postName"
          placeholder="请输入岗位名称"
          clearable
          size="small"
          @clear="loadPost"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="岗位状态" clearable size="small" @clear="loadPost">
          <el-option
            v-for="dict in postDict"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!--    添加按钮模块-->
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-plus" size="mini" :disabled="this.idList.length===0" @click="delGroup">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-plus" size="mini" @click="exportExcel()">导出
        </el-button>
      </el-col>
      <el-col :span="1.5" align="right">
        <right-toolbar :show-search.sync="showTable" @queryTable="reLoadPage"/>
      </el-col>
    </el-row>
    <br>
    <!--    文件导入模块-->
    <el-dialog
      title="excel导入"
      :visible.sync="flag"
      width="40%"
    >
      <el-col>
        <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload"/>
      </el-col>
      <el-button @click="flag = false">取 消</el-button>
      <el-button type="primary" @click="flag = false">确 定</el-button>
    </el-dialog>
    <el-table :data="postList" @selection-change="selsChange" @row-click="handleCurrentChange">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item"/>
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column label="岗位编号" align="center" prop="postId"/>
      <el-table-column label="岗位编码" align="center" prop="postCode"/>
      <el-table-column label="岗位名称" align="center" prop="postName"/>
      <el-table-column label="岗位排序" align="center" prop="postSort"/>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-if="scope.row.userId===1?false:true"
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="updateStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--添加修改会话弹出框-->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col>
            <el-form-item label="岗位名称" prop="postName">
              <el-input v-model="form.postName" placeholder="请输入岗位名称"/>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="岗位编码" prop="postCode">
              <el-input v-model="form.postCode" placeholder="请输入岗位编码"/>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="岗位排序" prop="postSort">
              <el-input-number
                v-model="form.postSort"
                placeholder="请输入序号"
                controls-position="right"
                :min="0"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="岗位状态">
              <el-radio v-model="form.status"
                        v-for="dict in postDict"
                        :key="dict.dictValue"
                        :label="dict.dictValue"
              >{{dict.dictLabel}}
              </el-radio>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--分页模块-->
    <el-pagination
      :page-sizes="[3, 10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @current-change="loadPost"
      @size-change="handleSizeChange"
    />
  </div>
</template>

<script>
    import UploadExcelComponent from '@/components/UploadExcel/index.vue'

    export default {
        name: 'PostView',
        components: {UploadExcelComponent},
        data() {
            return {
                // 分页参数
                total: 0,
                pageSize: 3,
                current: 1,
                // 标头
                title: '',
                // 是否显示 添加/修改 弹出窗口
                open: false,
                // 是否显示模糊查询框
                showTable: true,
                // 是否弹出文件导出框
                flag: false,
                // 模糊查询参数
                queryParams: {
                    postCode: '',
                    postName: '',
                    status: ''
                },
                postDicts: ['sys_normal_disable'],
                // 字典
                postDict: {
                    sys_normal_disable: '',
                    dictValue: '',
                    dictLabel: ''
                },
                // 多选删除id
                idList: [],
                // 字典状态码
                statusOptions: [],
                // 表单数据
                postList: [],
                tableHeader: [],
                // 表单参数
                form: {
                    postId: '',
                    postCode: '',
                    postName: '',
                    postSort: '',
                    status: '0',
                    createBy: '',
                    createTime: '',
                    updateBy: '',
                    updateTime: '',
                    remark: '',
                    isDelete: 0

                },
                rules: {
                    postName: [
                        {required: true, message: '岗位名称不能为空', trigger: 'blur'}
                    ],
                    postCode: [
                        {required: true, message: '岗位编码不能为空', trigger: 'blur'}
                    ],
                    post: [
                        {required: true, message: '岗位名称不能为空', trigger: 'blur'}
                    ]
                }
            }
        },
        created() {
            this.loadPost(this.current, this.pageSize)
        },
        methods: {
            // 获取页面数据
            loadPost: function (current, pageSize) {
                pageSize = this.pageSize
                this.axios.get('/post/page?current=' + current + '&pageSize=' + pageSize).then(res => {
                    this.postList = res.data.records
                    this.current = res.data.current
                    this.pageSize = res.data.size
                    this.total = res.data.total
                })
                // console.log(this.postDict)
                this.axios.get('/dict/maps/' + this.postDicts.join()).then(res => {
                    this.postDict = res.data.sys_normal_disable['dictData']
                })
            },
            // 添加按钮
            handleAdd() {
                this.open = true
                this.title = '岗位添加'
            },
            // 修改按钮
            handleUpdate(row) {
                this.form = row
                if (this.form.status !== '0') {
                    this.$message.error('岗位被停用，不允许修改操作，请先修改岗位状态')
                } else {
                    this.open = true
                    this.title = '岗位修改'
                    this.form = {
                        postId: row.postId,
                        postCode: row.postCode,
                        postName: row.postName,
                        postSort: row.postSort,
                        status: row.status,
                        createBy: row.createBy,
                        createTime: row.createTime,
                        updateBy: row.updateBy,
                        updateTime: row.updateTime,
                        remark: row.remark,
                        isDelete: row.isDelete
                    }
                }
            },
            // 表单确定按钮
            submitForm() {
                if (this.form.postId === '') {
                    if (this.form.postName === '' || this.form.postCode === '' || this.form.postSort === '') {
                        this.$message.info("信息未全部填写完成，提交失败！")
                    } else {
                        // console.log('_------------------------')
                        this.axios.post('/post/add', this.form).then(res => {
                            if (res.data === 'ok') {
                                this.$message.success('添加成功')
                                this.loadPost(this.current, this.pageSize)
                            }
                            console.log(res)
                        })
                        this.open = false
                        this.reset()
                    }
                } else {
                        this.axios.put('/post/update', this.form).then(res => {
                            if (res.data === 'ok') {
                                this.$message.success('修改成功!')
                                this.loadPost(this.current, this.pageSize)
                            } else {
                                this.$message.error("状态修改失败，岗位不为空")
                                this.loadPost(this.current, this.pageSize)
                            }
                        })
                        this.open = false
                        this.reset()

                    }
                // this.open = false
                // this.reset()
            },
            // 表单取消按钮
            cancel() {
                this.open = false
                this.reset()
            },
            // 清空表单数据
            reset() {
                this.form = {
                    postId: '',
                    postCode: '',
                    postName: '',
                    postSort: '',
                    status: '0',
                    createBy: '',
                    createTime: '',
                    updateBy: '',
                    updateTime: '',
                    remark: '',
                    isDelete: 0
                }
            },
            // 改变分页显示条数
            handleSizeChange(val) {
                // console.log(`每页 ${val} 条`);
                this.pageSize = val
                // console.log(this.pageSize);
                this.loadPost(this.current, this.pageSize)
            },
            // 模糊查询搜索按钮
            handleQuery() {
                this.axios.get('/post/query?postCode=' + this.queryParams.postCode + '&postName=' + this.queryParams.postName +
                    '&status=' + this.queryParams.status).then(res => {
                    this.postList = res.data
                })
            },
            // 模糊查询重置按钮
            resetQuery() {
                this.queryParams = {
                    postCode: '',
                    postName: '',
                    status: ''
                }
                this.loadPost(this.current, this.pageSize)
            },
            // 岗位状态修改
            updateStatus(row) {
                this.form = row
                this.axios.put('/post/update', this.form).then(res => {
                    if (res.data === 'ok') {
                        this.$message.success('状态修改成功！')
                    } else {
                        this.$message.error('状态修改失败，该岗位不为空！')
                        this.loadPost(this.current, this.pageSize)
                    }
                }),
                    this.axios.get('/dict/maps/' + this.postDicts.join()).then(res => {
                        this.postDict = res.data.sys_normal_disable['dictData']
                    })
                this.reset()
            },
            // 刷新页面
            reLoadPage() {
                this.loadPost(this.current, this.pageSize)
                this.$message.success('刷新成功！')
            },
            // 删除按钮
            handleDelete(row) {
                const lbb = this
                if (lbb.$confirm('确定要删除名称为' + row.postName + '的数据吗', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async function () {
                    const {data: res} = await lbb.axios.delete('post/delete/' + row.postId)
                    console.log(res)
                    if (res === 'ok') {
                        lbb.$message.success('删除成功！')
                        lbb.loadPost(lbb.current, lbb.pageSize)
                    } else {
                        lbb.$message.error('删除失败！岗位不是空的！')
                    }
                })) {
                }
            },
            // 选择性删除
            selsChange(idList) {
                this.idList = idList
                console.log(idList)
            },
            delGroup() {
                var ids = []
                const lb = this
                var num = lb.idList.length
                console.log(lb.idList.length)
                for (let i = 0; i < num; i++) {
                    if (i < num - 1) {
                        ids += lb.idList[i].postId + ','
                    } else {
                        ids += lb.idList[i].postId
                    }
                }
                if (lb.$confirm('是否删除岗位编号为' + ids + '的数据吗？', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async function () {
                    const {data: res} = await lb.axios.delete('/post/deleteAll/' + JSON.parse(JSON.stringify(ids)))
                    if (res === 'ok') {
                        lb.$message.success('删除成功')
                        lb.loadPost(lb.current, lb.pageSize)
                    } else {

                        lb.$message.error("删除失败，选择的岗位中编号为：" + res + "存在人员！")
                    }
                })) {
                }
            },
            // 导出excel
            exportExcel() {
                console.log('进到文件下载了')
                this.axios({
                    method: 'get',
                    url: 'http://localhost:8080/post/excel',
                    responseType: 'arraybuffer'
                }).then(res => {
                    // 使用Blob对象将后端返回的Arraybuffer格式得数据转成blob类型的数据 window.URL.createObjectURL(blob)可以把一个blob转成blobURL，用作图片显示，文件下载（不能再服务器上存储，只能在浏览器使用）
                    var b = new Blob([res.data], {type: 'application/vnd.ms-excel'})
                    // 使用URL对象将blob类型的数据生成一个在线下载的链接
                    var url = URL.createObjectURL(b)
                    // 然后我们使用a标签进行下载
                    var link = document.createElement('a')

                    // 设置导出的文件名
                    link.download = '岗位信息' + '.xlsx'
                    link.href = url
                    // 点击获取文件
                    link.click()
                })
            },
            handleSuccess({results, header}) {
                this.tableData = results
                this.tableHeader = header
            },
            handleCurrentChange(row, event, column) {
                this.$refs.table.toggleRowSelection(row)
            }
        }
    }
</script>

<style scoped>

</style>
